import Vue from 'vue'
import VueRouter from 'vue-router'
import MyLogin from '@/components/MyLogin/MyLogin.vue'
import MyHome from '@/components/MyHome/MyHome.vue'
import MyMain from '@/components/MyMain/MyMain.vue'
import MyUsers from '@/components/Users/MyUsers.vue'
import MyRights from '@/components/Rights/MyRights.vue'
import MyRoles from '@/components/Rights/MyRoles.vue'
import MyCategories from '@/components/Goods/MyCategories.vue'
import MyParams from '@/components/Goods/MyParams.vue'
import MyGoods from '@/components/Goods/MyGoods.vue'
import Add from '@/components/Goods/Add.vue'
import MyOrders from '@/components/MyOrders/MyOrders.vue'
import MyReports from '@/components/Reports/MyReports.vue'

Vue.use(VueRouter)

const routes = [{
    path: '/',
    redirect: '/login'
  },
  // 登录的路由规则
  {
    path: '/login',
    component: MyLogin
  },
  {
    path: '/home',
    component: MyHome,
    redirect: '/main',
    children: [{
      path: '/main',
      component: MyMain
    }, {
      path: '/users',
      component: MyUsers
    }, {
      path: '/rights',
      component: MyRights
    }, {
      path: '/roles',
      component: MyRoles
    }, {
      path: '/categories',
      component: MyCategories
    }, {
      path: '/params',
      component: MyParams
    }, {
      path: '/goods',
      component: MyGoods
    }, {
      path: '/goods/add',
      component: Add
    }, {
      path: '/orders',
      component: MyOrders
    }, {
      path: '/reports',
      component: MyReports
    }]
  }
]

const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  //to 将要访问的路径
  //from 从哪个路径访问的
  //next是一个函数 next()直接放行，next('/login’)强制跳转
  if (to.path === '/login') {
    return next()
  }
  if (to.path === '/home') {
    if (!window.sessionStorage.getItem('token')) {
      return next('/login')
    } else {
      return next()
    }
  }
  return next()

})
export default router
